package vikaa.timelinepackage;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.vikaa.pullview.PullToRefreshView;
import com.vikaa.pullview.PullToRefreshView.OnFooterRefreshListener;
import com.vikaa.pullview.PullToRefreshView.OnHeaderRefreshListener;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import vikaa.bean.TwitterHash;
import vikaa.bean.WowoTwitter_item;
import vikaa.tools.CalendarUtil;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.ValueClass;
import vikaa.ui.Mywowo;
import vikaa.wowo.R;
import vikaa.wowo.cache.TwitterSqlStoragePrivate;

public class TimelineImportWeibo extends Activity implements OnHeaderRefreshListener,OnFooterRefreshListener,OnItemClickListener{
	private ArrayList<WowoTwitter_item> twitterList = new ArrayList<WowoTwitter_item>();
	private ArrayList<TwitterHash> oldList ;
	private LinearLayout backBtn;
	private ImageView submitBtn;
	private GridView mGridView;
	private PullToRefreshView mPullToRefreshView;
	private AdapterTwitters adapter;
	private int page;
	private String space_id;
	private String weibo_uid;
	public static String role;
	public static UpdateTwitterThread utt;
	
	private LinearLayout header;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline_import_self_weibo);
		space_id = getIntent().getExtras().getString("space_id");
		weibo_uid = getIntent().getExtras().getString("weibo_uid");
		role = getIntent().getExtras().getString("role");
		initview();
		page = 1;
		initdata();
	}
	private void initview(){
		header =(LinearLayout)findViewById(R.id.header);
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				TwitterSqlStoragePrivate.dropchoosed(getApplicationContext());
				TwitterSqlStoragePrivate.dropRemoveTwitter(getApplicationContext());
			}
		});
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					ArrayList<WowoTwitter_item> addList = TwitterSqlStoragePrivate.getchoosedTwitterFromSql(getApplicationContext());
					ArrayList<String> romoveList = TwitterSqlStoragePrivate.getRemoveListFromSql(getApplicationContext());
					JSONArray removeTwitters = new JSONArray();
					JSONArray addTwitters = new JSONArray();
					if(addList.size() >0 || romoveList.size()>0){
						DialogService.showProgressDialog(TimelineImportWeibo.this, "正在导入");
						for(String hash:romoveList){
							removeTwitters.put(hash);
						}
						for(WowoTwitter_item item:addList){
							addTwitters.put(item.getIdstr());
						}
						new UpdateTwitterThread(addTwitters.toString(), removeTwitters.toString(), space_id).start();
					}
					else//choose no photo
						finish();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		mPullToRefreshView = (PullToRefreshView)findViewById(R.id.main_pull_refresh_view);
		mGridView = (GridView)findViewById(R.id.gridview);
		adapter = new AdapterTwitters(TimelineImportWeibo.this,getLayoutInflater(),twitterList);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
	}
	private void initdata(){
		ArrayList<WowoTwitter_item> temp = new ArrayList<WowoTwitter_item> ();
		if ((temp=TwitterSqlStoragePrivate.getmyTwitterFromSql(getApplicationContext())).size()>0 && false){ 
			Message msg = mhandler.obtainMessage(2);
			msg.obj = temp;
			msg.sendToTarget();
	    }
	    else{
			//DialogService.showProgressDialog(TimelineImportWeibo.this, getString(R.string.get_photo));
			new GetAlreadyTimelineThread(space_id).start();
	    }
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				new GetWeiboTimelineThread(space_id, weibo_uid, String.valueOf(page)).start();
				break;
			case 2:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				//twitterList.clear();
				if(msg.obj != null){
					ArrayList<WowoTwitter_item> strings = (ArrayList<WowoTwitter_item>) msg.obj;
					if(!strings.isEmpty()){
						twitterList.addAll(strings);
						adapter.notifyDataSetChanged();
					}
				}
				break;
			case 3:
				DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(TimelineImportWeibo.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineImportWeibo.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				Toast.makeText(TimelineImportWeibo.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				Toast.makeText(TimelineImportWeibo.this, "no twitters", Toast.LENGTH_SHORT).show();
				break;
			case 6:
				DialogService.closeProgressDialog();
				TwitterSqlStoragePrivate.dropchoosed(getApplicationContext());
				TwitterSqlStoragePrivate.dropRemoveTwitter(getApplicationContext());
				TwitterSqlStoragePrivate.dropmyTwitter(getApplicationContext());
				finish();
				Timeline.isimport = true;
				Mywowo.isrefresh = true;
				break;
			case 7:
				DialogService.closeProgressDialog();
				if(msg.obj != null){
					Toast.makeText(TimelineImportWeibo.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineImportWeibo.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 8:
				DialogService.closeProgressDialog();
				Toast.makeText(TimelineImportWeibo.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	class GetWeiboTimelineThread extends Thread{
		private String space_id;
		private String weibo_uid;
		private String page;
		private boolean isrun = true;
		public GetWeiboTimelineThread(String space_id, String weibo_uid,
				String page) {
			super();
			this.space_id = space_id;
			this.weibo_uid = weibo_uid;
			this.page = page;
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				isrun  = false;
				try{
					Map<String, String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					map.put("weibo_uid", weibo_uid);
					map.put("page", page);
					map.put("type", "1");
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/selecttimeline", map));
					if(jsonObj.getString("result").equals("1")){
						if(jsonObj.getString("info").length() < 10){
							Message msg = mhandler.obtainMessage(5);
							msg.sendToTarget();
						}
						JSONArray twitters = jsonObj.getJSONArray("info");
						if(twitters.length()>1){
							ArrayList<WowoTwitter_item> tempList = new ArrayList<WowoTwitter_item>();
							for(int i=0;i<twitters.length();i++){
								if(twitters.getJSONObject(i).getString("thumbnail_pic").length() > 5){
									WowoTwitter_item item = new  WowoTwitter_item();
									item.setBmiddle_pic(twitters.getJSONObject(i).getString("bmiddle_pic"));
									item.setCreated_at(twitters.getJSONObject(i).getString("created_at"));
									item.setHash(twitters.getJSONObject(i).getString("hash"));
									item.setIdstr(twitters.getJSONObject(i).getString("idstr"));
									item.setOriginal_pic(twitters.getJSONObject(i).getString("original_pic"));
									item.setText(twitters.getJSONObject(i).getString("text"));
									item.setThumbnail_pic(twitters.getJSONObject(i).getString("thumbnail_pic"));
									if(oldList.size()>0){
										for(TwitterHash hash:oldList){
											if(item.getHash().equals(hash.getHash())){
												item.setSelected(true);
												item.setState(true);
												break;
											}
											else{
												item.setSelected(false);
												item.setState(false);
											}
										}
									}
									tempList.add(item);
								}
							}
							TwitterSqlStoragePrivate.SavemyTwitterInSql(tempList, getApplicationContext());
							Message msg = mhandler.obtainMessage(2);
							msg.obj = tempList;
							msg.sendToTarget();
						}
						else{
							Message msg = mhandler.obtainMessage(5);//no twitters
							msg.sendToTarget();
						}
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);//no twitters
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class GetAlreadyTimelineThread extends Thread{
		private String space_id;
		private boolean isrun = true;
		public GetAlreadyTimelineThread(String space_id) {
			super();
			this.space_id = space_id;
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				oldList = new ArrayList<TwitterHash>();
				isrun  = false;
				try{
					Map<String, String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/TwitterList", map));
					if(jsonObj.getString("result").equals("1")){
						if(jsonObj.getString("info").length() < 10){
							Message msg = mhandler.obtainMessage(1);
							msg.sendToTarget();
						}
						JSONObject info = jsonObj.getJSONObject("info");
						Iterator it = info.keys();  
						while (it.hasNext()) {  
							TwitterHash th = new TwitterHash();
				            String key = it.next().toString(); 
				            th.setHash(key);
				            th.setState(info.getString(key));
				            oldList.add(th);
						}
						Message msg = mhandler.obtainMessage(1);
						msg.sendToTarget();
						
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class UpdateTwitterThread extends Thread{
		private String addTwitters;
		private String removeTwitters;
		private String space_id;
		private boolean isrun=true;
		public UpdateTwitterThread(String addTwitters, String removeTwitters,
				String space_id) {
			super();
			this.addTwitters = addTwitters;
			this.removeTwitters = removeTwitters;
			this.space_id = space_id;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				Map<String, String> map = new HashMap<String, String>();
				map.put("space_id", space_id);
				map.put("addTwitters", addTwitters);
				map.put("removeTwitters", removeTwitters);
				try{
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"twitter/spacetwitterchange", map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(6);
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(7);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(8);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	public void onFooterRefresh(PullToRefreshView view) {
		page++;
		new GetWeiboTimelineThread(space_id, weibo_uid, String.valueOf(page)).start();
		mPullToRefreshView.postDelayed(new Runnable() {
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
			}
		},5000);
	}
	public void onHeaderRefresh(PullToRefreshView view) {
		TwitterSqlStoragePrivate.dropmyTwitter(getApplicationContext());
		new GetAlreadyTimelineThread(space_id).start();
		mPullToRefreshView.postDelayed(new Runnable() {
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete("更新于:"+ CalendarUtil.Date2String(new Date(Calendar.getInstance().getTimeInMillis()), ValueClass.PULL_REFRESH_TIME));
			}
		},5000);
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		//TwitterSqlStoragePrivate.updatemyTwitterSql(twitterList.get(position), !(twitterList.get(position).isSelected()), getApplicationContext());
		if(!(twitterList.get(position).isState())){
			if(!(twitterList.get(position).isSelected()) )
				TwitterSqlStoragePrivate.saveChoosedinSql(twitterList.get(position), getApplicationContext());
			else
				TwitterSqlStoragePrivate.delectChoosedinSql(twitterList.get(position), getApplicationContext());
		}
		else{
			if(twitterList.get(position).isSelected())
				TwitterSqlStoragePrivate.saveRemoveList(twitterList.get(position).getHash(), getApplicationContext());
			else
				TwitterSqlStoragePrivate.delectRemoveList(twitterList.get(position).getHash(), getApplicationContext());
		}
		adapter.changeState(position,view);
	}
}
